import React, { useState, useEffect } from 'react';
import styles from './index.less';
import NewsCard from '../../components/newsCard';
import { useDispatch, useSelector } from 'dva';
import InViewPort from '../../components/InViewPort';
import { Tabs } from 'antd-mobile';
import { useIntl, getLocale } from 'umi';
import ReturnIndex from "../../components/returnIndex"

function Index() {
  const dispatch = useDispatch();
  const { newsList, newsPageIndex, newsLastPage, userInfo, articleCategoryList = [] } = useSelector(
    ({ index }) => index,
  );
  const [buttonIndex, setButtonIndex] = useState(0);
  const [listData, setListDate] = useState();
  const intl = useIntl();
  const lang = () => getLocale()?.split('-')[0]?.toUpperCase();

  useEffect(() => {
    dispatch({
      type: 'index/apiGetArticleCategoryList',
      payload: {
        language: lang(),
      },
      isReset: true,
    });
  }, [userInfo]);

  useEffect(() => {
    if (!!articleCategoryList.length) {
      handelButton(articleCategoryList?.[0], buttonIndex);
    }
  }, [articleCategoryList]);

  function handelButton(item, index) {
    setButtonIndex(index);
    dispatch({
      type: 'index/apiGetNews',
      payload: {
        page: 0,
        pageSize: 10,
        userId: userInfo?.user?.id,
        categoryId: getLocale() == "zh-CN" ? "503902149353279486" : "503902149353279488"
      },
      isReset: true,
    });
  }

  function onEnter() {
    if (newsPageIndex < newsLastPage) {
      dispatch({
        type: 'index/apiGetNews',
        payload: {
          pageSize: 10,
          page: newsPageIndex + 1,
          userId: userInfo?.user?.id,
          categoryId: getLocale() == "zh-CN" ? "503902149353279486" : "503902149353279488"
        },
      });
    }
  }

  return (
    <div className={styles.page}>
      <ReturnIndex/>
      <div className={styles.myBody}>
        {newsList &&
          newsList.map((item, index) => {
            if (index == newsList.length - 1) {
              return (
                <InViewPort key={index} onEnter={onEnter}>
                  <NewsCard obj={item}  type={1}></NewsCard>
                </InViewPort>
              );
            }
            return <NewsCard key={index} obj={item}  type={1}></NewsCard>;
          })}
      </div>
    </div>
  );
}

export default Index;
